{% extends '1.html' %}
{% block content %}
    <div class="login-page-body">
        <div class="login-page-container">
            <div class="login-page-header">
                <h1>欢迎回来</h1>
                <p>登录您的账户以继续</p>
            </div>

            <div class="login-page-section">
                <h2 class="login-page-section-title">用户登录</h2>

                <div class="login-page-error-message" id="errorMessage">
                    用户名或密码错误，请重试
                </div>

                <div class="login-page-success-message" id="successMessage">
                    登录成功！正在跳转...
                </div>

                <form id="loginForm">
                    <div class="login-page-form-group">
                        <label class="login-page-form-label" for="username">用户名 / 邮箱</label>
                        <input type="text" id="username" class="login-page-form-input" placeholder="请输入用户名或邮箱" required>
                    </div>

                    <div class="login-page-form-group">
                        <label class="login-page-form-label" for="password">密码</label>
                        <input type="password" id="password" class="login-page-form-input" placeholder="请输入密码" required>
                    </div>

                    <div class="login-page-form-checkbox">
                        <input type="checkbox" id="remember">
                        <label for="remember">记住我</label>
                        <a href="#">忘记密码？</a>
                    </div>

                    <button type="submit" id="loginBtn" class="login-page-btn">登 录</button>
                </form>
                <div class="login-page-register-link">
                    还没有账户？ <a href="{% url 'shopper:logout' %}">立即注册</a>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 登录API配置
        const LoginAPI = {
            // 登录接口URL - 请替换为实际的API地址
            loginUrl: '/shopper/api/login/',
            // 刷新token接口URL
            refreshTokenUrl: '/api/auth/refresh',
            // 请求超时时间（毫秒）
            timeout: 10000,
            // token存储键名
            tokenKey: 'loginPageAuthToken',
            // 用户信息存储键名
            userKey: 'loginPageUserInfo',
            // 记住用户名键名
            rememberKey: 'loginPageRememberedUser'
        };

        // 登录管理器
        const LoginManager = {
            // 初始化
            init: function() {
                this.bindEvents();
                this.checkRememberedUser();
                this.checkTokenValidity();
            },

            // 绑定事件
            bindEvents: function() {
                const form = document.getElementById('loginForm');
                if (form) {
                    form.addEventListener('submit', this.handleSubmit.bind(this));
                }

                const inputs = document.querySelectorAll('.login-page-form-input');
                inputs.forEach(input => {
                    input.addEventListener('focus', this.handleInputFocus.bind(this));
                    input.addEventListener('blur', this.handleInputBlur.bind(this));
                });

                // 回车键提交
                document.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter' && !this.isLoading) {
                        this.handleSubmit(e);
                    }
                });
            },

            // 处理表单提交
            handleSubmit: async function(e) {
                e.preventDefault();

                if (this.isLoading) return;

                const username = document.getElementById('username').value.trim();
                const password = document.getElementById('password').value;
                const remember = document.getElementById('remember').checked;

                // 表单验证
                if (!this.validateForm(username, password)) {
                    return;
                }

                // 显示加载状态
                this.setLoading(true);
                this.hideMessages();

                try {
                    // 发送登录请求
                    const response = await this.sendLoginRequest(username, password);

                    // 处理登录成功
                    this.handleLoginSuccess(response, remember);

                } catch (error) {
                    // 处理登录失败
                    this.handleLoginError(error);
                } finally {
                    this.setLoading(false);
                }
            },

            // 表单验证
            validateForm: function(username, password) {
                if (!username) {
                    this.showError('请输入用户名或邮箱');
                    return false;
                }

                if (!password) {
                    this.showError('请输入密码');
                    return false;
                }

                if (password.length < 1) {
                    this.showError('密码长度不能少于1位');
                    return false;
                }

                return true;
            },

            // 发送登录请求
            sendLoginRequest: async function(username, password) {
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), LoginAPI.timeout);

                try {
                    const response = await fetch(LoginAPI.loginUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({
                            username: username,
                            password: password,
                            rememberMe: document.getElementById('remember').checked
                        }),
                        signal: controller.signal
                    });

                    clearTimeout(timeoutId);

                    if (!response.ok) {
                        const errorData = await response.json().catch(() => ({}));
                        throw new Error(errorData.message || `HTTP ${response.status}:${response.statusText}`);
                    }

                    return await response.json();

                } catch (error) {
                    clearTimeout(timeoutId);

                    if (error.name === 'AbortError') {
                        throw new Error('请求超时，请检查网络连接');
                    }

                    if (error instanceof TypeError) {
                        throw new Error('网络连接失败，请检查网络设置');
                    }

                    throw error;
                }
            },

            // 处理登录成功
            handleLoginSuccess: function(data, remember) {
                // 存储token和用户信息
                if (data.token) {
                    localStorage.setItem(LoginAPI.tokenKey, data.token);
                }

                if (data.refreshToken) {
                    localStorage.setItem('loginPageRefreshToken', data.refreshToken);
                }

                if (data.user) {
                    localStorage.setItem(LoginAPI.userKey, JSON.stringify(data.user));
                }

                // 记住用户名
                if (remember) {
                    localStorage.setItem(LoginAPI.rememberKey, document.getElementById('username').value);
                } else {
                    localStorage.removeItem(LoginAPI.rememberKey);
                }

                // 显示成功消息
                this.showSuccess('登录成功！正在跳转...');

                // 跳转到主页或指定页面
                setTimeout(() => {
                    const redirectUrl = new URLSearchParams(window.location.search).get('redirect') || 'http://127.0.0.1:8000/shopper/api/loginsuss/';
                    window.location.href = redirectUrl;
                }, 1500);
            },

            // 处理登录错误
            handleLoginError: function(error) {
                console.error('登录错误:', error);

                let errorMessage = '登录失败，请重试';

                if (error.message) {
                    if (error.message.includes('401')) {
                        errorMessage = '用户名或密码错误';
                    } else if (error.message.includes('403')) {
                        errorMessage = '账户已被禁用，请联系管理员';
                    } else if (error.message.includes('429')) {
                        errorMessage = '登录尝试次数过多，请稍后再试';
                    } else if (error.message.includes('网络')) {
                        errorMessage = error.message;
                    } else {
                        errorMessage = error.message;
                    }
                }

                this.showError(errorMessage);
                this.shakeForm();
            },

            // 检查token有效性
            checkTokenValidity: async function() {
                const token = localStorage.getItem(LoginAPI.tokenKey);
                if (!token) return;

                try {
                    // 这里可以添加验证token有效性的逻辑
                    // 例如发送请求到后端验证token
                    const response = await fetch('/api/auth/verify', {
                        headers: {
                            'Authorization': `Bearer ${token}`
                        }
                    });

                    if (response.ok) {
                        // Token有效，直接跳转
                        const redirectUrl = new URLSearchParams(window.location.search).get('redirect') || '/dashboard';
                        window.location.href = redirectUrl;
                    } else {
                        // Token无效，清除存储
                        this.clearAuthData();
                    }
                } catch (error) {
                    console.error('Token验证失败:', error);
                    // 不清除token，可能是网络问题
                }
            },

            // 清除认证数据
            clearAuthData: function() {
                localStorage.removeItem(LoginAPI.tokenKey);
                localStorage.removeItem('loginPageRefreshToken');
                localStorage.removeItem(LoginAPI.userKey);
            },

            // 检查记住的用户名
            checkRememberedUser: function() {
                const rememberedUser = localStorage.getItem(LoginAPI.rememberKey);
                if (rememberedUser) {
                    const usernameInput = document.getElementById('username');
                    const rememberCheckbox = document.getElementById('remember');
                    if (usernameInput) usernameInput.value = rememberedUser;
                    if (rememberCheckbox) rememberCheckbox.checked = true;
                }
            },

            // 设置加载状态
            setLoading: function(loading) {
                this.isLoading = loading;
                const loginBtn = document.getElementById('loginBtn');
                const inputs = document.querySelectorAll('.login-page-form-input');

                if (loading) {
                    loginBtn.classList.add('login-page-btn-loading');
                    loginBtn.disabled = true;
                    inputs.forEach(input => input.disabled = true);
                } else {
                    loginBtn.classList.remove('login-page-btn-loading');
                    loginBtn.disabled = false;
                    inputs.forEach(input => input.disabled = false);
                }
            },

            // 输入框焦点效果
            handleInputFocus: function(e) {
                e.target.parentElement.style.transform = 'scale(1.02)';
            },

            handleInputBlur: function(e) {
                e.target.parentElement.style.transform = 'scale(1)';
            },

            // 显示错误消息
            showError: function(message) {
                const errorMsg = document.getElementById('errorMessage');
                if (errorMsg) {
                    errorMsg.textContent = message;
                    errorMsg.style.display = 'block';
                }
            },

            // 显示成功消息
            showSuccess: function(message) {
                const successMsg = document.getElementById('successMessage');
                if (successMsg) {
                    successMsg.textContent = message;
                    successMsg.style.display = 'block';
                }
            },

            // 隐藏所有消息
            hideMessages: function() {
                const errorMsg = document.getElementById('errorMessage');
                const successMsg = document.getElementById('successMessage');
                if (errorMsg) errorMsg.style.display = 'none';
                if (successMsg) successMsg.style.display = 'none';
            },

            // 表单抖动效果
            shakeForm: function() {
                const form = document.querySelector('.login-page-section');
                if (form) {
                    form.style.animation = 'loginPageShake 0.5s';
                    setTimeout(() => {
                        form.style.animation = '';
                    }, 500);
                }
            }
        };

        // 社交登录
        function socialLogin(platform) {
            const messages = {
                'wechat': '正在跳转到微信登录...',
                'qq': '正在跳转到QQ登录...',
                'weibo': '正在跳转到微博登录...'
            };

            // 创建临时提示
            const tempMsg = document.createElement('div');
            tempMsg.className = 'login-page-success-message';
            tempMsg.style.display = 'block';
            tempMsg.textContent = messages[platform];
            tempMsg.style.position = 'fixed';
            tempMsg.style.top = '20px';
            tempMsg.style.left = '50%';
            tempMsg.style.transform = 'translateX(-50%)';
            tempMsg.style.zIndex = '1000';
            document.body.appendChild(tempMsg);

            // 构建OAuth URL
            const oauthUrls = {
                'wechat': '/api/auth/oauth/wechat',
                'qq': '/api/auth/oauth/qq',
                'weibo': '/api/auth/oauth/weibo'
            };

            setTimeout(() => {
                tempMsg.remove();
                // 跳转到OAuth授权页面
                window.location.href = oauthUrls[platform] || '#';
            }, 1000);
        }

        // 添加CSS动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes loginPageShake {
                0%, 100% { transform: translateX(0); }
                10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
                20%, 40%, 60%, 80% { transform: translateX(5px); }
            }
            @keyframes loginPageSpin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        `;
        document.head.appendChild(style);

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            LoginManager.init();
        });

        // 导出登录管理器供其他脚本使用
        window.LoginManager = LoginManager;
    </script>
{% endblock content %}
